package com.alkin.thing.project.system.service.impl;

import com.alkin.thing.common.utils.MyListUtils;
import com.alkin.thing.project.system.domain.SysDictData;
import com.alkin.thing.project.system.mapper.SysDictDataMapper;
import com.alkin.thing.project.system.service.ISysDictDataService;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Calendar;
import java.util.List;
import java.util.UUID;

/**
 * 字典 业务层处理
 * 
 * @author huangzy
 */
@Service
public class SysDictDataServiceImpl implements ISysDictDataService
{
    @Autowired
    private SysDictDataMapper dictDataMapper;


    // 设备图片保存路径
    public static final String devicePrefix = "dict_device_imgPath";

//    @Value("${upload-file-path}")
    private String uploadFilePath;

    /**
     * 根据条件分页查询字典数据
     * 
     * @param dictData 字典数据信息
     * @return 字典数据集合信息
     */
    @Override
    public List<SysDictData> selectDictDataList(SysDictData dictData)
    {
        return dictDataMapper.selectDictDataList(dictData);
    }

    /**
     * 根据字典类型查询字典数据
     * 
     * @param dictType 字典类型
     * @return 字典数据集合信息
     */
    @Override
    public List<SysDictData> selectDictDataByType(String dictType)
    {
        return dictDataMapper.selectDictDataByType(dictType);
    }

    /**
     * 根据字典类型和字典键值查询字典数据信息
     * 
     * @param dictType 字典类型
     * @param dictValue 字典键值
     * @return 字典标签
     */
    @Override
    public String selectDictLabel(String dictType, String dictValue)
    {
        return dictDataMapper.selectDictLabel(dictType, dictValue);
    }

    /**
     * 根据字典数据ID查询信息
     * 
     * @param dictCode 字典数据ID
     * @return 字典数据
     */
    @Override
    public SysDictData selectDictDataById(Long dictCode)
    {
        return dictDataMapper.selectDictDataById(dictCode);
    }

    /**
     * 通过字典ID删除字典数据信息
     * 
     * @param dictCode 字典数据ID
     * @return 结果
     */
    @Override
    public int deleteDictDataById(Long dictCode)
    {
        return dictDataMapper.deleteDictDataById(dictCode);
    }

    /**
     * 批量删除字典数据信息
     * 
     * @param dictCodes 需要删除的字典数据ID
     * @return 结果
     */
    public int deleteDictDataByIds(Long[] dictCodes)
    {
        return dictDataMapper.deleteDictDataByIds(dictCodes);
    }

    /**
     * 新增保存字典数据信息
     * 
     * @param dictData 字典数据信息
     * @return 结果
     */
    @Override
    public int insertDictData(SysDictData dictData)
    {
        return dictDataMapper.insertDictData(dictData);
    }

    /**
     * 修改保存字典数据信息
     * 
     * @param dictData 字典数据信息
     * @return 结果
     */
    @Override
    public int updateDictData(SysDictData dictData)
    {
        return dictDataMapper.updateDictData(dictData);
    }

    @Override
    public String uploadFile(SysDictData sysDict, MultipartFile imgFile) throws IOException {
        String destFilePath = null;
        //删除旧文件
        if (null != sysDict && null != sysDict.getImgPath() && !"".equals(sysDict.getImgPath())) {
            File oldFile = new File(uploadFilePath + File.separator + sysDict.getImgPath());
            if (oldFile.exists())
                oldFile.delete();
            destFilePath = sysDict.getImgPath();
        }else{
            String srcFileName = imgFile.getOriginalFilename();
            String[] surfix = srcFileName.split("\\.");
            String destName = UUID.randomUUID().toString() + "." + surfix[surfix.length - 1];

            Calendar now = Calendar.getInstance();
            String year = String.valueOf(now.get(Calendar.YEAR));
            String month = String.valueOf(now.get(Calendar.MONTH) + 1);
            String day = String.valueOf(now.get(Calendar.DAY_OF_MONTH));

            StringBuffer destDir = new StringBuffer(File.separator).append(year)
                    .append(File.separator).append(month)
                    .append(File.separator).append(day);
            File typeDir = new File(uploadFilePath + File.separator + devicePrefix + destDir);
            if (!typeDir.exists()) {
                typeDir.mkdirs();
            }
            destFilePath = File.separator + devicePrefix + destDir + File.separator + destName;
        }
        imgFile.transferTo(new File(uploadFilePath + destFilePath));
        return destFilePath;
    }

    @Override
    public int importExcel(MultipartFile file, String dictType) {
        XSSFWorkbook book = null;
        InputStream in = null;
        try {
            in = file.getInputStream();
            book = new XSSFWorkbook(in);
            XSSFSheet sheet = book.getSheetAt(0);
            int endRow = sheet.getLastRowNum();
            for (int i=1; i<=endRow; i++){
                XSSFRow row = sheet.getRow(i);
                String name = row.getCell(0).getStringCellValue();
                String value = row.getCell(1).getStringCellValue();
                SysDictData dictData = new SysDictData();
                dictData.setDictLabel(name);
                dictData.setDictValue(value);
                dictData.setDictType(dictType);
                dictDataMapper.insertDictData(dictData);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if (null != in)
                    in.close();
                if (null != book)
                    book.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return 1;
    }

    @Override
    public void downloadExcel(HttpServletResponse response, String type) {
        XSSFWorkbook book = null;
        OutputStream out = null;
        try {
            book = new XSSFWorkbook();
            XSSFSheet sheet = book.createSheet();
            XSSFRow row = sheet.createRow(0);
            row.createCell(0, CellType.STRING).setCellValue("字典名称");
            row.createCell(1, CellType.STRING).setCellValue("字典值");
            if ("device_model".equals(type)){
                row.createCell(2, CellType.STRING).setCellValue("设备宽");
                row.createCell(3, CellType.STRING).setCellValue("设备高");
                row.createCell(4, CellType.STRING).setCellValue("设备模型");
            }

            List<SysDictData> list = dictDataMapper.selectDictDataByType(type);
            if (MyListUtils.isNotEmpty(list)){
                for (SysDictData d : list) {
                    row = sheet.createRow(sheet.getLastRowNum() + 1);
                    row.createCell(0, CellType.STRING).setCellValue(d.getDictLabel());
                    row.createCell(1, CellType.STRING).setCellValue(d.getDictValue());
                    if ("device_model".equals(type)){
                        row.createCell(2, CellType.NUMERIC).setCellValue(null == d.getWidth() ? 0 : d.getWidth());
                        row.createCell(3, CellType.NUMERIC).setCellValue(null == d.getHeight() ? 0 : d.getHeight());
                        row.createCell(4, CellType.STRING).setCellValue(null == d.getDeviceModel() ? "" : d.getDeviceModel());
                    }
                }
            }
            out=response.getOutputStream();
            response.reset();
            response.setHeader("Content-disposition", "attachment; filename="+type+".xlsx");
            response.setContentType("application/msexcel");
            book.write(out);
            out.close();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                if (null != book)
                    book.close();
                if (null != out)
                    out.close();
            }catch (Exception e) {
            }
        }
    }
}
